package com.scoutmobmap.server;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class MineDataServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
    private static Logger logger = Logger.getLogger("foo");
    private static List<Offer> offerList = null;

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
      ObjectifyService.register(Offer.class);
      ObjectifyService.register(OfferList.class);
      Objectify ofy = ObjectifyService.begin();

      resp.setContentType("text/plain");
      if (req.getParameter("delete") != null) {
        deleteAllData(ofy);
        resp.getWriter().println("All Offers Deleted");
      }
      if (req.getParameter("read") != null) {
        updateOffers(ofy, resp.getWriter());
       }
    }

    private Offer getOffer(Objectify ofy, String id) {
      return ofy.get(Offer.class, id);
    }
    
    private void deleteAllData(Objectify ofy) {
      Iterable<Key<Offer>> allKeys = ofy.query(Offer.class).fetchKeys();
      ofy.delete(allKeys);
      OfferList.deleteOfferList(ofy);
    }
    
    private void updateOffers(Objectify ofy, PrintWriter pw) {
      boolean isNew = OfferList.updateOfferList(ofy);
      if (isNew) { pw.println("OfferList Not Cached - refetching"); }
      OfferList offerList = OfferList.getOfferList(ofy);
      
      Set<String> allOffers = offerList.offerIds;
      pw.println(allOffers.size() + " Offers found");
      for (String o : allOffers) { pw.println(o); }
      
      Iterable<Key<Offer>> allKeys = ofy.query(Offer.class).fetchKeys();
      for (Key<Offer> offerKey : allKeys) {
        String id = offerKey.getName();
        if (allOffers.contains(id)) {
          allOffers.remove(id);
        } else {
          // This offer has expired, delete it
          ofy.delete(offerKey);
        }
      }
      
      for (String id : allOffers) {
        Offer offer = Offer.addOffer(ofy, id);
        pw.println("ADDING: " + offer.toString());
      }
      pw.println("ALL DONE!");
    }
    

    
  
}
